//
//  UserAccount.swift
//  weibo001
//
//  Created by ios on 15/11/7.
//  Copyright © 2015年 ios. All rights reserved.
//

import UIKit

class UserAccount: NSObject,NSCoding {
//用户昵称
    var screen_name:String?
    //用户头像地址
    var avatar_large:String?
    
    var access_token: String?
    var expires_in: NSTimeInterval = 0 {
        didSet {
        expires_date = NSDate(timeIntervalSinceNow: expires_in)
        
        }
    }
    var uid: String?
    
    var expires_date: NSDate?
    
    init(dict:[String:AnyObject]) {
        super.init()
        
        setValuesForKeysWithDictionary(dict)
        
        
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    
    override var description: String {
    
    let keys = ["access_token", "expires_in","uid","expires_date","screen_name","avatar_large"]
    
        return dictionaryWithValuesForKeys(keys).description
    }
    
    
    //MARK:  归档解档保存
    //归档 ，保存数据到磁盘
    
    func encodeWithCoder(aCoder: NSCoder) {
   aCoder.encodeObject(access_token, forKey: "access_token")
   aCoder.encodeObject(expires_date, forKey: "expires_date")
    aCoder.encodeObject(uid, forKey: "uid")
    aCoder.encodeObject(screen_name, forKey: "screen_name")
    aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        
    }
    // 在 extension 中只允许写 便利构造函数，而不能写指定构造函数
    // 不能定义存储型属性，定义存储型属性，会破坏类本身的结构！
    
    //解档  required` - 没有继承性，所有的对象只能解档出当前的类对象
    required init?(coder aDecoder: NSCoder) {
        
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires_date = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
        uid = aDecoder.decodeObjectForKey("uid") as? String
        screen_name = aDecoder.decodeObjectForKey("screen_name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
        
        
    }
    
    
    //MARK: 保存数据
    
    func saveUserAccount() {
    //1. 保存路径 取出沙盒路径
        var path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last!
        
        path = (path as NSString).stringByAppendingPathComponent("account.plist")
    
    print(path)
        
        //归档保存
        
        NSKeyedArchiver.archiveRootObject(self, toFile: path)
    
    
    }
    
    
}








